# coding=utf-8
from django.shortcuts import render
from django.http import JsonResponse

from common import functions
from services import TaskTradeService

from app.services import UserLoginDecorator
from utils.code_msg import codeMsg

# Create your views here.


@UserLoginDecorator.login_require
def calculate_task(request):
    task_id = request.POST.get('task_id', 0)
    user_id = request.token_store.get('user_id')

    trade_amount = TaskTradeService.calculate_task(task_id, user_id)
    return JsonResponse(dict({
        'status': trade_amount.get('status'),
        'data': trade_amount.get('msg')
    }, **codeMsg['calculate_amount']))


def pay_task(request):
    """
    发布任务之后支付押金和max(任务酬金、任务预算)
    """
    trade_num = request.POST.get('trade_num')
    user_id = request.token_store.get('user_id')
    trade_fare = request.POST.get('trade_fare')
    pay_way = request.POST.get('pay_way')
    pay = TaskTradeService.pay_task(user_id, trade_num, float(trade_fare), pay_way)
    if pay.get('status') is True:
        del pay['msg']
        pay['data'] = ''
        return JsonResponse(dict(
            pay, **codeMsg['pay_success']
        ))
    else:
        pay['data'] = functions.get_form_errors(pay.get('msg'))
        del pay['msg']
        return JsonResponse(dict(
            pay, **codeMsg['pay_error']
        ))


@UserLoginDecorator.login_require
def grant_money(request):
    """
    发放酬金 
    """
    task_id = request.POST.get('task_id', 0)
    grant_way = TaskTradeService.grant(task_id)
    return JsonResponse({
        'status': grant_way,
        'code': 200,
        'data': '',
        'message': '',
    })
